<script setup lang="ts">
import { getProject } from '@/api/exam/project';
import { QuestionType } from '@/api/exam/template/types';
import { ProjectVO } from '@/api/exam/project/types';
import { addAnswer, getAnswer, listAnswerByProject, tempSave, updateAnswer } from '@/api/exam/answer';
import { AnswerVO } from '@/api/exam/answer/types';
import { UAParser } from 'ua-parser-js';
import { getChooseLabel } from '@/utils/tagColor';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { exam_question_type } = toRefs<any>(proxy?.useDict('exam_question_type'));
const route = useRoute();

const project = ref<any | ProjectVO>(
  {
    survey: {
      children: []
    },
    setting: {
      answerSetting: {
        onePageOneQuestion: false
      },
      submittedSetting: {},
      examSetting: {}
    }
  }
);
const loading = ref(false);
// 分页状态
const currentPage = ref(0);

const answerInfo = ref<AnswerVO>(null);

const getAnswerInfo = async (id) => {
  const res = await getAnswer(id);
  answerInfo.value = res.data;
  getAnswerAnswer();
  tempAnswerToAnswer(answerInfo.value);
};

// 根据survey生成answer
const getAnswerAnswer = () => {
  if (answerInfo.value !== null && answerInfo.value.answer === null) {
    answerInfo.value.tempAnswer = {};
    answerInfo.value.survey.children.forEach(child => {
      if ([QuestionType.TrueFalse, QuestionType.Radio, QuestionType.Checkbox].includes(child.type)) {
        answerInfo.value.tempAnswer[child.id] = [];
      }
      if ([QuestionType.MultipleBlank, QuestionType.FillBlank, QuestionType.Textarea].includes(child.type)) {
        answerInfo.value.tempAnswer[child.id] = {};
      }
    });
  }
};

// 计算属性
const totalPages = computed(() => {
  return answerInfo.value?.survey.children.length || 0;
});
// 获取作答情况
const answering = ref(0);
const total = ref(0);
const answered = ref(0);
//计算进度条
const getProgressBar = () => {
  total.value = 0;
  answered.value = 0;
  // 总题数
  total.value = answerInfo.value.survey.children.length;
  // 已作答
  for (const value of Object.values(answerInfo.value.tempAnswer)) {
    if ((Array.isArray(value) && value.length > 0) ||
      (typeof value === 'object' && value !== null && Object.keys(value).length > 0) ||
      (typeof value === 'string' && value.trim() !== '')) {
      answered.value++;
    }
  }
  return Math.round(answered.value / total.value * 100);
};
watch(
  () => answerInfo.value?.tempAnswer,
  () => {
    answering.value = getProgressBar();
  },
  { deep: true }
);
// 点击答题卡切题
const handleSheetItem = (item, index) => {
  currentPage.value = index;
};

// 判断答题卡作答状态
const getSheetItemStatus = (key) => {
  let value = answerInfo.value.tempAnswer[key];
  return (Array.isArray(value) && value.length > 0) ||
    (typeof value === 'object' && value !== null && Object.keys(value).length > 0) ||
    (typeof value === 'string' && value.trim() !== '');
};

// 监听题目变化重置页码
// watch(() => project.value.survey.children, () => {
//   currentPage.value = 0;
// });
const buttonLoading = ref(false);
const tempSubmit = async () => {
  buttonLoading.value = true;
  // 处理答案
  tempAnswerToAnswer(answerInfo.value);
  await tempSave(answerInfo.value).finally(() => {
    buttonLoading.value = false;
    proxy?.$modal.notifySuccess('暂存成功');
  });
};

const tempAnswerToAnswer = (temp) => {
  let answer = {};
  for (const [key, value] of Object.entries(temp.tempAnswer)) {
    if (
      (typeof value === 'string' && value === '') ||
      (Array.isArray(value) && value.length === 0) ||
      (typeof value === 'object' && value !== null && Object.keys(value).length === 0)
    ) {
      continue;
    }
    const question = temp.survey.children.find(q => q.id === key);
    if (question) {
      if (question.type === 'Radio' || question.type === 'TrueFalse') {
        answer[key] = { [value]: true };
      } else if (question.type === 'Checkbox') {
        answer[key] = {};
        value.forEach(option => {
          answer[key][option] = true;
        });
      } else {
        answer[key] = value;
      }
    }
  }
  answerInfo.value.answer = answer;
};

onMounted(async () => {
  await getAnswerInfo(route.params && route.params.id as string);
  // await getAnswerInfo();
});
</script>

<template>
  <div class="survey">
    <div class="survey-antd">
      <div class="preview-body">
        <div v-if="answerInfo" v-for="(template, index) in answerInfo.survey.children" class="template-item">
          <div class="p-4 mt-2 vertical" :id="template.id">
            <a-flex justify="space-between">
              <el-text size="small">第 {{ index + 1 }} 题</el-text>
              <a-flex justify="end" gap="small" align="center">
                <el-tag v-if="answerInfo.examInfo.questionScore[template.id]!==0" type="success">
                  得分: {{ answerInfo.examInfo.questionScore[template.id] }}
                </el-tag>
                <svg-icon v-if="answerInfo.examInfo.questionScore[template.id]=== template.attribute.examScore"
                          icon-class="true" color="#00bf6f" />
                <svg-icon v-else icon-class="false" color="#ff6d56" />
              </a-flex>
            </a-flex>
            <!-- 题目标题 -->
            <div class="preview-title">
              <el-text tag="b" size="large">
                {{ template.title || '未命名题目' }}
              </el-text>
            </div>
            <div class="data-edit-content">
              <a-radio-group v-if="template.type === QuestionType.Radio ||template.type === QuestionType.TrueFalse"
                             v-model:value="answerInfo.tempAnswer[template.id]">
                <a-row :gutter="[16,8]">
                  <a-col :span="24" v-for="(item,i) in template.children"
                         :class="{'right-answer': item.attribute.examCorrectAnswer===answerInfo.tempAnswer[template.id]&&answerInfo.tempAnswer[template.id]===item.id,
                                       'wrong-answer': item.attribute.examCorrectAnswer!==answerInfo.tempAnswer[template.id]&&answerInfo.tempAnswer[template.id]===item.id}"
                         class="default-radio-answer">
                    <a-radio size="large" :value="item.id" @click.prevent>
                      <span class="ml-2">{{ getChooseLabel(i) + item.title }}</span>
                    </a-radio>
                  </a-col>
                </a-row>
              </a-radio-group>
              <a-checkbox-group v-if="template.type ===QuestionType.Checkbox"
                                v-model:value="answerInfo.tempAnswer[template.id]">
                <a-row :gutter="[16,8]">
                  <a-col v-for="(item, idx) in template.children" :key="idx" :span="24"
                         :class="{'right-answer':  answerInfo.tempAnswer[template.id].includes(item.attribute.examCorrectAnswer) && answerInfo.tempAnswer[template.id].includes(item.id),
                           'wrong-answer': !answerInfo.tempAnswer[template.id].includes(item.attribute.examCorrectAnswer) && answerInfo.tempAnswer[template.id].includes(item.id),}"
                         class="default-checkbox-answer">
                    <a-checkbox :value="item.id" @click.prevent>
                      {{ item.title }}
                    </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
              <div v-if="template.type === QuestionType.MultipleBlank || template.type === QuestionType.FillBlank">
                <a-row :gutter="[16,8]">
                  <a-col v-for="(option, idx) in template.children" :key="idx" :span="24">
                    <a-input v-model:value="answerInfo.tempAnswer[template.id][option.id]" readonly />
                  </a-col>
                </a-row>
              </div>
              <div v-if="template.type ===QuestionType.Textarea">
                <a-row :gutter="[16,8]">
                  <a-col v-for="(option, idx) in template.children" :key="idx" :span="24">
                    <a-textarea v-model:value="answerInfo.tempAnswer[template.id][option.id]"
                                :autosize="{ minRows: 2, maxRows: 6 }" resize="none" readonly />
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </div>

      </div>
      <a-card class="answer-sheet" v-if="answerInfo">
        <template #title>
          <div class="answer-sheet-header">
            答题卡
          </div>
        </template>
        <a :href="'#'+key" v-for="(value, key,index) in answerInfo.examInfo['questionScore']"
           class="answer-sheet-item item-danger"
           :class="{ 'item-success': answerInfo.examInfo['questionScore'][key]===answerInfo.survey.children[index].attribute.examScore }">
          {{ index + 1 }}
        </a>

      </a-card>
    </div>
  </div>

</template>

<style scoped lang="scss">
.survey {
  height: 100%;
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #f7f8fa;
  background-repeat: no-repeat;
  background-position: top center;
  background-size: cover;
  background-attachment: fixed;
}

.survey-antd {
  position: relative;
  max-width: 780px;
  margin: 32px auto;
  padding-bottom: 60px;
  white-space: pre;
  background-color: var(--el-bg-color);
  border-color: #aab2bd;
  border-width: 0px;
  border-radius: 8px;
  box-shadow: 0 2px 12px #0000000f;
}

.answer-sheet {
  position: fixed;
  top: 64px;
  width: 200px;
  max-height: 400px;
  margin-left: -52px;
  box-shadow: 0 2px 6px #0000000a;
  transform: translate(-100%);

  .answer-sheet-header {
    position: relative;
    display: flex;
    align-items: center;
    color: #484848;
    font-size: 14px;
  }

  .answer-sheet-header:before {
    display: inline-block;
    width: 2px;
    height: 12px;
    margin-right: 6px;
    background: var(--el-color-primary);
    border-radius: 2px;
    content: "";
  }

  .answer-sheet-footer {
    padding: 0 18px;
    color: #707070;
    font-size: 12px;
    line-height: 12px;

    .finished:before {
      display: inline-block;
      width: 8px;
      height: 8px;
      margin-right: 4px;
      background: var(--el-color-primary-light-9);
      border: 1px solid var(--el-color-primary-light-5);
      border-radius: 50%;
      content: "";
    }

    .un-finished:before {
      display: inline-block;
      width: 8px;
      height: 8px;
      margin-right: 4px;
      background: #fff;
      border: 1px solid #d8d8d8;
      border-radius: 50%;
      content: "";
    }
  }
}

.answer-sheet-item {
  position: relative;
  float: left;
  box-sizing: border-box;
  width: 28px;
  height: 28px;
  margin: 6px 6px 6px 0;
  color: #484848;
  font-size: 12px;
  line-height: 26px;
  white-space: nowrap;
  text-align: center;
  background: #fff;
  border: 1px solid #d8d8d8;
  border-radius: 50%;
  cursor: pointer;
}

.item-danger {
  color: var(--el-color-danger);
  background: var(--el-color-danger-light-9);
  border-color: var(--el-color-danger-light-5);
}

.item-success {
  color: var(--el-color-success);
  background: var(--el-color-success-light-9);
  border-color: var(--el-color-success-light-5);
}

.template-item {
  white-space: normal; /* 允许换行 */
  word-break: break-word; /* 强制单词内换行（长单词/URL） */
  overflow-wrap: break-word; /* 兼容性更好 */
}

.one-page-container {
  overflow-y: auto;
}

.preview-progress {
  padding: 14px 16px;
  background-color: var(--el-bg-color);
}

.preview-title {
  margin: 16px 0;
}

.preview-content {
  max-height: 50vh;
  min-height: 30vh;

  .ant-radio, .ant-checkbox-wrapper {
    white-space: pre-wrap;
  }

}


.preview-body {
  padding: 14px 72px 24px;
}

.pagination-control {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
  padding: 15px;
  border-radius: 4px;
}

.page-info {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
  text-align: center;
}

.data-edit-content {
  margin-top: 14px;

  .ant-radio-group, .ant-checkbox-group {
    width: 100%;
  }
}
</style>
<style lang="scss">
.right-answer {
  color: #00bf6f !important;
  background: rgba(0, 191, 111, .05) !important;
  border: 1px solid rgba(0, 191, 111, .3) !important;
  border-radius: 4px;

  .ant-checkbox-checked .ant-checkbox-inner, .ant-radio-checked .ant-radio-inner {
    background-color: rgb(0, 191, 111) !important;
    border-color: rgb(0, 191, 111) !important;
  }

  .ant-checkbox-checked:after {
    border: 1px solid rgb(0, 191, 111) !important;
  }
}

.wrong-answer {
  color: #ff6d56 !important;
  background: rgba(255, 109, 86, .05) !important;
  border: 1px solid rgba(255, 109, 86, .3) !important;
  border-radius: 4px;

  .ant-checkbox-checked .ant-checkbox-inner, .ant-radio-checked .ant-radio-inner {
    background-color: #ff6d56 !important;
    border-color: #ff6d56 !important;
  }

  .ant-checkbox-checked:after {
    border: 1px solid #ff6d56 !important;
  }

}

.wrong-answer-background {
  color: #ff6d56 !important;
  background: rgba(255, 109, 86, .05) !important;
  border: 1px solid rgba(255, 109, 86, .3) !important;
  border-radius: 4px;
}
</style>

